const code = -221;
function throwError(ctx, message) {
  ctx.body = {
    code,
    message: message || "Token已失效",
  };
  ctx.status = 200;
}

module.exports = () => {
  return async function auth(ctx, next) {
    const token = ctx.headers.authorization || "";

    if (!token) {
      return throwError(ctx);
    }

    let userId

    try {
      const res = await ctx.service.auth.getCurrentUser();
      userId = res.userId
    } catch (error) {
      throwError(ctx)
    }

    if (!ctx.session[userId]) {
      return throwError(ctx);
    } else {
      await next();
    }

  };
};
